package io.sdl.controller;


import io.sdl.common.sys.dto.SdlInstitutionDTO;
import io.sdl.common.sys.dto.SdlInstitutionPicDTO;
import io.sdl.common.sys.entity.SdlDoctorsEntity;
import io.sdl.common.sys.entity.SdlInstitutionEntity;
import io.sdl.common.sys.service.SdlDoctorsService;
import io.sdl.common.sys.service.SdlInstitutionPicService;
import io.sdl.common.sys.service.SdlInstitutionService;
import io.sdl.common.sys.vo.SdlInstitutionVo;
import io.sdl.common.utils.Result;
import io.sdl.dto.CheckDto;
import io.sdl.dto.DictDTO;
import io.sdl.entity.RoleUserEntity;
import io.sdl.entity.SysRoleEntity;
import io.sdl.entity.TokenEntity;
import io.sdl.entity.UserEntity;
import io.sdl.service.RoleUserService;
import io.sdl.service.SysDictDataService;
import io.sdl.service.SysRoleService;
import io.sdl.service.TokenService;
import io.sdl.vo.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class ApiSdlInstitutionController {

	@Autowired
	private SdlInstitutionService sdlInstitutionService;

	@Autowired
	private SysDictDataService sysDictDataService;

	@Autowired
	private TokenService tokenService;

	@Autowired
	private SysRoleService sysRoleService;

	@Autowired
	private RoleUserService roleUserService;



	@GetMapping("find/institutions")
	@Operation(summary = "获取机构列表")
	public Result findAllInstitutions(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {

		//机构类型筛选
		if (params.get("institutionType").equals("全部")) {
			params.put("institutionType", null);
		} else {
			DictDTO dictValue = sysDictDataService.getDictValue("institution_type", (String) params.get("institutionType"));
			params.put("institutionType", dictValue.getDictValue());
		}

		params.put("page", Integer.valueOf((String) params.get("page")) - 1);
		params.put("pageSize", Integer.valueOf((String) params.get("pageSize")));

		List<SdlInstitutionVo> all = sdlInstitutionService.findAll(params);
		if (params.get("sort").equals("评分最高")) {
			all = all.stream().sorted(Comparator.comparing(SdlInstitutionVo::getInstitutionProevalution).reversed()).collect(Collectors.toList());
		}
		return new Result().ok(all);
	}


	/*
	 * file  图片文件
	 * id    机构id
	 *Identification 图片字段区分标识
	 */
	@PostMapping("upload/certificate")
	@Operation(summary = "图片上传")
	public Result uploadPatient(@RequestParam(value = "file", required = false) MultipartFile file, Long id, String identification) {
		try {
			sdlInstitutionService.saveUploadedFile(file, id, identification);


			return new Result().ok("图片上传成功");
		} catch (Exception e) {
			return new Result().error(500, "文件上传失败: " + e.getMessage());

		}
	}


    @PostMapping("sub/check")
    @Operation(summary = "提交审核")
    public Result submitReview(@RequestBody CheckDto dto) {

		TokenEntity byToken = tokenService.getByToken(dto.getToken());
		if(byToken==null){
			return new Result().error(400, "长时间未操作,请重新登录");
		}
		SdlInstitutionEntity entity = new SdlInstitutionEntity();
		//当前时间
		Date now = new Date();
		//待审核状态
		entity.setIsDel(2);
		//创建人
		entity.setCreater(byToken.getUserId());
		entity.setCreateTime(now);
		entity.setInstitutionAddress(dto.getInstitutionAddress());
		SdlInstitutionEntity sdlInstitutionEntity = sdlInstitutionService.numberCheck(dto.getBusinessLicenseNumber());
		if(sdlInstitutionEntity !=null){
			if(sdlInstitutionEntity.getIsDel() == 2){
				return new Result().ok( "正在审核,请勿重复提交");
			}
			if(sdlInstitutionEntity.getIsDel() == 1){
				return new Result().ok( "该机构已注册,无法重复注册");
			}

		}
		//营业执照编号
		entity.setBusinessLicenseNumber(dto.getBusinessLicenseNumber());
		entity.setInstitutionType(dto.getInstitutionType());
		entity.setInstitutionPhone(dto.getInstitutionPhone());
		entity.setInstitutionMailbox(dto.getInstitutionMailbox());
		entity.setInstitutionData(dto.getInstitutionData());
		entity.setInstitutionCreater(dto.getInstitutionCreater());
		entity.setInstitutionIntro(dto.getInstitutionIntro());
		entity.setInstitutionName(dto.getInstitutionName());
		sdlInstitutionService.insert(entity);

		RoleUserEntity roleUserEntity = new RoleUserEntity();

		List<RoleUserEntity> roleList = roleUserService.getRoleUsersByRoleId(byToken.getUserId());
		if (roleList.size() > 0) {
			return new Result<UserInfoVo>().error(400, "每个微信号最多只能拥有一个角色");
		}
		//角色绑定
		if(dto.getRole().equals("institutionAdmin")){
			SysRoleEntity roleByRemark = sysRoleService.getRoleByRemark(dto.getRole());
			roleUserEntity.setUserId(byToken.getUserId());
			roleUserEntity.setRoleId(roleByRemark.getId());

		}
		roleUserEntity.setCreateDate(now);
		roleUserService.insert(roleUserEntity);
		return new Result().ok(entity.getInstitutionId());
    }
}
